package com.omenkk.juc.AQS;

import com.omenkk.juc.execute.ThreadPool;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
//基于AQS构建的同步器
@Slf4j
public class MySync extends AbstractQueuedSynchronizer {

    //尝试获取锁
    @Override
    protected boolean tryAcquire(int arg) {
//arg=1是我们制定的规范
        if(arg==1){
            //基于cas思想该将state=0改为1,获取锁
            if(compareAndSetState(0,1)){
                //锁对应线程
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
        }
        log.debug("获取锁失败，直接返回");
        return false;
    }

    //释放锁
    @Override
    protected boolean tryRelease(int arg) {
        if(arg==1){
            if(getState()==0){
                throw new IllegalStateException();//释放锁时，state必须为1
            }
            setExclusiveOwnerThread(null);//释放锁
            setState(0);
           // compareAndSetState(1,0);
            return true;
        }
        return false;
    }

    //返回一个条件变量，可以用于线程通信
    protected Condition newCondition(){
        return new ConditionObject();
    }

    @Override
    protected boolean isHeldExclusively() {
      return getState()==1;//锁是否被线程持有
    }
}
